<template>
  <div ref="chartContainer" class="chart-container"></div>
</template>

<script lang="ts" setup>
import * as echarts from 'echarts';
import { ref, onMounted, onBeforeUnmount } from 'vue';
import { ElMessage } from 'element-plus';
import { getClubTypeCountAPI } from '@/apis/club';

const chartContainer = ref<HTMLDivElement | null>(null);
let myChart = null;

const loadChartData = async () => {
  try {
    const response = await getClubTypeCountAPI();
    if (response.code === 0) {
      const data = response.data;
      // 将对象转换为数组格式
      const chartData = [
        { value: data.academic, name: '学术类' },
        { value: data.art, name: '艺术类' },
        { value: data.volunteer, name: '公益类' },
        { value: data.culture, name: '文化类' },
        { value: data.recreation, name: '娱乐类' },
        { value: data.career, name: '职业发展类' },
        { value: data.other, name: '其他类' },
      ];
      updateChart(chartData); // 更新图表数据
    } else {
      ElMessage.error(`加载社团统计量失败: ${response.message}`);
    }
  } catch (error) {
    ElMessage.error('加载社团统计量失败');
    console.error(error);
  }
};

const updateChart = (chartData) => {
  if (myChart) {
    const option = {
      title: {
        text: '社团统计量',
        left: 60,
        top: 10,
        textStyle: {
          fontSize: 24,
          fontWeight: 'bold',
        },
      },
      tooltip: {
        trigger: 'item',
      },
      legend: {
        top: 'bottom',
      },
      toolbox: {
        show: true,
        feature: {
          mark: { show: true },
          dataView: { show: true, readOnly: false },
          restore: { show: true },
          saveAsImage: { show: true },
        },
      },
      series: [
        {
          name: '社团统计量',
          type: 'pie',
          radius: [50, 200],
          center: ['50%', '50%'],
          roseType: 'area',
          itemStyle: {
            borderRadius: 8,
          },
          label: {
            show: true,
            formatter: '{b}: {c}',
            fontSize: 14,
            color: '#000',
          },
          labelLine: {
            show: true,
          },
          data: chartData,
        },
      ],
    };
    myChart.setOption(option);
  }
};

onMounted(() => {
  if (chartContainer.value) {
    myChart = echarts.init(chartContainer.value);
    loadChartData();
  }
});

onBeforeUnmount(() => {
  if (myChart) {
    myChart.dispose();
  }
});
</script>

<style scoped>
:deep(.el-main) {
  background-color: #e6f3ff;
  padding: 20px;
  flex: 1;
  overflow: auto;
  position: relative;
}

.main-content {
  color: white;
}

.chart-container {
  width: 100%;
  height: 500px;
  margin-top: 20px;
}
</style>